<template>
  <BaseDialog :title="(!props.item.messageId ? '新增' : '查看') + '停电信息'" :handleCancel="handleCancel"
    :dialogVisible="props.dialogVisible" width="1100px">
    <el-form :class="props.item.messageId ? 'detail' : ''" ref="ruleFormRef" :model="ruleForm" :rules="rules"
      label-width="120px" class="demo-ruleForm" status-icon @submit="submitForm">
      <el-row :gutter="20">
        <el-col :span="11" style="border-right: 1px solid #ddd">
          <el-form-item label="标题" prop="title">
            <el-input placeholder="请输入标题" :disabled="!isEdit" type="text" v-model="ruleForm.title" />
          </el-form-item>
          <el-form-item label="停电时间" prop="date">
            <el-date-picker style="width: 100%"  v-model="ruleForm.date"
              type="datetimerange" :disabled="!isEdit"  range-separator="~"
              value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始时间" end-placeholder="结束时间" :default-time="[
                new Date(0, 0, 0, 0, 0, 0),
                new Date(0, 0, 0, 23, 59, 59),
              ]" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input placeholder="请输入内容" :disabled="!isEdit" type="textarea" :autosize="{ minRows: 4, maxRows: 7 }"
              v-model="ruleForm.content" />
          </el-form-item>
          <el-form-item label="相关台区" prop="lineDtoList">
            <el-input ref="selectPop" :placeholder="!props.item.messageId ? '请选择相关台区，多选' : ''
              " @click="selectCommunity" readonly v-if="isEdit" v-model="ruleForm.lineDtoList" />
            <areaTag :disabled="!isEdit" v-model:list="communityList"  v-if="communityList&&communityList.length>0"/>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="相关群聊" class="right" style="margin-bottom: 0px">
            <el-row v-if="!isEdit">
              <el-col :span="24">
                <el-form-item label="审核状态">
                  <el-select
                    v-model="searchParams.auditStatus"
                    placeholder="全部"
                    @change="handleSearch"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="待审核" value="0" />
                    <el-option label="审核通过" value="1" />
                    <el-option label="审核不通过" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="发送状态">
                  <el-select
                    v-model="searchParams.sendStatus"
                    placeholder="全部"
                    @change="handleSearch"
                  >
                    <el-option label="全部" value="" />
                    <el-option label="未发送" value="0" />
                    <el-option label="已发送" value="1" />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="24" style="padding: 10px 0; text-align: right">

                <span style="padding: 0 16px"
                  >待审核：<span style="color: #02a7f0fe">{{
                    count.waitAuditNum
                  }}</span></span
                >
                <span style="padding: 0 16px"
                  >审核通过：<span style="color: #70b603fe">{{
                    count.auditPassNum
                  }}</span></span
                >
                <span style="padding: 0 16px"
                  >审核不通过：<span style="color: #d9001bfe">{{
                    count.auditNotPassNum
                  }}</span></span
                >
              </el-col>
            </el-row>
          </el-form-item>
          <el-table ref="baseTable" :data="tableData" width="560px" size="small" v-loading="loading">
            <el-table-column type="index" label="序号" width="60" :index="indexMethod">
            </el-table-column>
            <el-table-column prop="wxGroupName" label="微信群名称" />
            <el-table-column prop="communityDtoList" label="相关片区/村社" width="160">
              <template #default="scope">
                <span>
                  {{
                    (
                      scope.row.communityDtoList ||
                      scope.row.recordCommunityDtoList ||
                      []
                    )
                      .map((e) => e.communityName)
                      ?.join('、')
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="managerDtoList" label="关联网格经理" width="120">
              <template #default="scope">
                <span>
                  {{
                    (
                      scope.row.managerDtoList ||
                      scope.row.recordManagerDtoList ||
                      []
                    )
                      .map((e) => e.managerName)
                      ?.join('、')
                  }}
                </span>
              </template>
            </el-table-column>
            <template v-if="isEdit">
              <el-table-column prop="isPowerAudit" label="是否需要审核">
                <template #default="scope">
                  <span>{{ scope.row.isPowerAudit == 0 ? '是' : '否' }}</span>
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column prop="auditStatus" label="审核状态">
                <template #default="scope">
                  <span
                    :style="{
                      color: getAuditStatus(scope.row.auditStatus).color,
                    }"
                    >{{ getAuditStatus(scope.row.auditStatus).text }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column prop="sendStatus" label="审核人">
                <template #default="scope">
                  {{ scope.row.auditStatus === 1 || scope.row.auditStatus === 2? scope.row.recordManagerDtoList[0].managerName : '/' }}
                </template>
              </el-table-column>
              <el-table-column prop="sendStatus" label="审核时间">
                <template #default="scope">
                  {{ scope.row.auditTime || '/' }}
                </template>
              </el-table-column>
            </template>

          </el-table>
          <Pages v-if="!isEdit" :small="true" v-model:page="page" :getTableData="getTableData"></Pages>
        </el-col>
      </el-row>
      <div class="form-btn" v-if="!props.item.messageId">
        <el-button @click="handleCancel"> 取 消 </el-button>
        <el-button type="primary" :loading="btnLoading" native-type="submit">
          确 定
        </el-button>
      </div>
    </el-form>
  </BaseDialog>
  <AssociatedArea v-if="visibleAssociatedCommunity" v-model:dialogVisible="visibleAssociatedCommunity"
    v-model:selecedList="communityList" :item="item" title="选择台区" ></AssociatedArea>
  <FilesDetail v-if="fielsVisible" v-model:dialogVisible="fielsVisible" :url="fileUrl"></FilesDetail>
</template>
<script setup lang="ts">
import FilesDetail from '@/components/filesDetals.vue'
import areaTag from '@/components/AssociatedArea/areaTag.vue'
import type { FormInstance } from 'element-plus'
import { contentManagementService } from '@/api/contentManagement'
import { commonService } from '@/api/common'
import { Debounce } from '@/hooks/throttle'
import { getAuditStatus, getSendStatus } from '@/hooks/getStateName'
import { download } from '@/hooks/downLoad'
import openMsgBox from '@/hooks/messageBox.js'
import AssociatedArea from '@/components/AssociatedArea/index.vue'
const indexMethod = (index: number) => {
  return index + 1
}
const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  item: {
    type: Object,
  },
  handleSearch: {
    type: Function,
  },
  type: {
    type: String,
  },
})
const fielsVisible = ref(false)

const loading = ref(false)
const fileUrl = ref('')
const communityList = ref([])
const searchParams = ref({
  auditStatus: '',
  sendStatus: '',
})

const page = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
})

const isEdit = computed(() => !props.item.messageId)
const tableData = ref([])
const count = ref({
  hasSendNum: 0,
  waitAuditNum: 0,
  notSendNum: 0,
})
const getmessageGroupRecordGetCount = () => {
  contentManagementService
    .messageGroupRecordGetCount({
      data: {
        messageId: props.item.messageId,
        auditStatus: searchParams.value.auditStatus,
        sendStatus: searchParams.value.sendStatus,
      },
    })
    .then((res) => {
      count.value = res.data
    })
}
const handleSearch = () => {
  page.currentPage = 1
  getTableData()
  getmessageGroupRecordGetCount()
}
const getTableData = async () => {
  loading.value = true
  try {
    if (isEdit.value) {
      const res = await commonService.getGroupCommunityInfoDtoList({
        data: communityList.value.map((e) => e.areaId),
      })
      tableData.value = res.data
    } else {
      const res = await contentManagementService.messageGroupRecordPageList({
        data: {
          messageId: props.item.messageId,
          auditStatus: searchParams.value.auditStatus,
          sendStatus: searchParams.value.sendStatus,
        },
        pageSize: page.pageSize,
        pageNumber: page.currentPage,
      })
      tableData.value = res.data.content
      page.total = res.data.total * 1
    }
    loading.value = false
  } catch (error) {
    loading.value = false
  }
}
const btnLoading = ref(false)
watch(
  () => [...communityList.value],
  Debounce((val) => {
    if (!props.item.messageId) {
      ruleForm.value.lineDtoList = communityList.value
        .map((e) => e.areaName)
        .join(',')
      if (val) {
        getTableData()
      } else {
        tableData.value = []
      }
    }
  }, 500),
  { flush: 'post' }
)
const emit = defineEmits(['update:dialogVisible'])
const visibleAssociatedCommunity = ref(false)
const selectPop = ref(null)
watch(visibleAssociatedCommunity, (val) => {
  if (val) selectPop.value.blur()
})
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  messageId: '',
  title: '',
  content: '',
  date:'',
  lineDtoList: '',
})

const rules = reactive({
  title: [{ required: true, message: '请输入', trigger: 'change' }],
  content: [{ required: true, message: '请输入', trigger: 'change' }],
  date:[{ required: true, message: '请选择', trigger: 'change' }],
  lineDtoList: [{ required: true, message: '请选择', trigger: 'change' }],
})
const selectCommunity = () => {
  visibleAssociatedCommunity.value = true
}
const submitForm = (e) => {
  e.preventDefault()
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      btnLoading.value = true
      contentManagementService
        .saveMessage({
          data: {
            messageSaveDto: {
              messageType: 1,
              content: ruleForm.value.content,
              title: ruleForm.value.title,
            },
            startTime:ruleForm.value.date[0],
            endTime:ruleForm.value.date[1],
            areaIdList: communityList.value.map((e) => e.areaId),

            communityDtoList: undefined,

          },
        })
        .then(() => {
          btnLoading.value = false
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          handleCancel()
          props.handleSearch()
        })
        .catch(() => {
          btnLoading.value = false
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleCancel = () => {
  emit('update:dialogVisible', false)
}
onMounted(() => {
  if (props.item.messageId) {
    ruleForm.value.messageId = props.item.messageId
    ruleForm.value.title = props.item.title
    ruleForm.value.content = props.item.content
    if(props.item.startTime&&props.item.endTime){
      ruleForm.value.date=[props.item.startTime,props.item.endTime]

    }
    // ruleForm.value.communityIdList = props.item.communityIdList
    communityList.value = props.item.gridAreaDtoList
    getTableData()
    getmessageGroupRecordGetCount()

  }
})
</script>
<style lang="scss" scoped>
.detail {
  :deep(.el-form-item__label:before) {
    content: ' ' !important;
  }
}

.right {
  &> :deep(.el-form-item__label) {
    width: auto !important;
  }
}

:deep(.el-input__validateIcon) {
  display: none;
}

.files {
  display: flex;
  font-size: 12px;

  .name {
    flex: 1;
    width: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
